<?php
/**
 * Created by PhpStorm.
 * User: zouhua
 * Date: 2017/5/4
 * Time: 15:20
 */

namespace app\controllers;


use app\components\WebController;
use app\models\ActivityApply;
use app\models\Banner;
use app\models\Favorite;
use app\models\Job;
use Yii;

class JobController extends WebController {

    public function beforeAction($action) {
        if (!parent::beforeAction($action)) {
            return FALSE;
        }
        if ($action->id === 'index') {
            $tag = $this->getParam('tag');
            if (NULL === $tag) {
                \Yii::$app->request->setQueryParams(['tag' => Job::TYPE_JOB]);
                $tag = Job::TYPE_JOB;
            }
            $banners = [
                Job::TYPE_JOB => Banner::TYPE_JOB,
                Job::TYPE_PRACTICE => Banner::TYPE_PRACTICE,
            ];
            $banner_type = isset($banners[$tag]) ? $banners[$tag] : Banner::TYPE_JOB;
            $this->view->params['banner_type'] = $banner_type;
        }
        return TRUE;
    }

    public function actions() {
        $tag = $this->get('tag');
        if (!isset(Job::$typeLabels[$tag])) {
            $tag = Job::TYPE_JOB;
        }
        return [
            'index' => [
                'class' => 'app\actions\UserList',
                'title' => Job::$typeLabels[$tag],
                'where' => ['type' => $tag, 'status' => Job::STATUS_SUCCESS],
                'modelClass' => Job::className(),
                'sort' => SORT_ASC
            ]
        ];
    }

    public function actionDetail() {
        $id = intval($this->get('id'));
        $model = Job::findOne($id);
        if (!$model) {
            return $this->redirect(["{$this->id}/"]);
        }

        $isFavorite = Favorite::getIsFavorite(ActivityApply::OWN_JOB, $id, $this->user);
        $isApply = $model->getIsApply($this->user);

        $tag = Job::$typeLabels[$model->type];
        $this->view->title = "{$tag}详情";
        $user = $this->user;
        $this->layout = 'page2';
        return $this->render(compact('model', 'user', 'isFavorite', 'isApply'));
    }

    public function actionApply() {
        $id = intval($this->get('id'));
        $model = Job::findOne($id);
        if (!$model || !$this->isAjax()) {
            return $this->redirect(["{$this->id}/"]);
        }
        if (Yii::$app->user->isGuest) {
            return $this->error('请先登录');
        }
        if (!$this->user->getIsStudent()) {
            return $this->error('只有学生可以报名');
        }
        if ($model->getIsApply($this->user)) {
            return $this->error('非法操作');
        }
        return ActivityApply::saveJobApply($model, $this->user);
    }
}